<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="employeeSearch" class="demo-form-inline">
        <!--条件查询-->
        <el-form-item >
          <el-input v-model="employeeSearch.ename" placeholder="员工姓名"></el-input>
        </el-form-item>

        <el-form-item >
          <el-select v-model="employeeSearch.id" placeholder="所在部门">
            <el-option label="所有部门" value="0"></el-option>
            <el-option :label="d.dpName" :value="d.id" v-for="d in departList" :key="d.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search"  plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addEmployee">添加员工</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="employeeList"
          style="width: 100%"
          @selection-change="handleSelectionChange" >
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="员工编号"
            align="center"
            prop="eid"
            width="180"/>
        <el-table-column
            label="姓名"
            prop="ename"
            align="center"/>
        <el-table-column
            label="年龄"
            prop="eage"
            align="center"/>
        <el-table-column
            label="工资"
            prop="esalary"
            align="center"/>
        <el-table-column
            label="所在部门"
            prop="departName"
            align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页导航面板-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <!--新增/编辑对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="employee" :rules="rules" ref="ruleForm">
        <el-form-item label="员工姓名" prop="ename" :label-width="formLabelWidth">
          <el-input v-model="employee.ename" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工年龄" prop="eage" :label-width="formLabelWidth">
          <el-input v-model.number="employee.eage" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工工资" prop="esalary" :label-width="formLabelWidth">
          <el-input v-model.number="employee.esalary" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在部门" prop="edepart" :label-width="formLabelWidth">
          <el-select v-model="employee.id" placeholder="请选择所在部门">
            <el-option label="所有部门" value="0"></el-option>
            <el-option :label="d.dpName" :value="d.id" v-for="d in departList" :key="d.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEmployee">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import employeeApi from "@/api/employee"
import departApi from "@/api/depart"
export default {
  data() {
    let checkAge = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('年龄不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('年龄必须为数字值'))
      } else if (value < 1 || value > 200) {
        return callback(new Error('年龄必须在1-200之间'))
      } else {
        callback()
      }
    }
    return {
      employeeList: [],
      page: 1,        // 当前页
      pageSize: 5,    // 每页显示记录条数
      total: 100,     // 总记录数
      employeeSearch:{}, // 查询条件对象
      departList:[],   // 所有部门
      ids:[], //选中的员工ID
      employee: {
        ename: '',
        eage: null,
        edepart: null, // 初始化 edepart 属性
      },       // 代表添加或修改的员工对象
      title: '',  //对话框标题
      dialogFormVisible:false,
      formLabelWidth: '120px',  // 代表表单的标签宽度formLabelWidth: '120px',  // 代表表单的标签宽度
      rules: {
        // 校验员工姓名
        ename: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' },
        ],
        // 校验员工年龄
        eage: [
          { validator: checkAge, trigger: 'blur' }
        ],
        esalary: [
          { required: true, message: '请输入员工薪资', trigger: 'blur' },
        ],
        // 校验员工部门
        'employee.id': [
          { required: true, message: '请选择员工部门', trigger: 'blur' },
        ]
      }
    }
  },
  created() {
    this.search()
    this.findAllDepart()
  },
  methods: {
    // 1. 查询所有员工
    async findEmployees() {
      const {data:res} = await employeeApi.findAllEmployees()
      console.log(res)
      if (data.code === 200) {
        this.employeeList = res.data.list
      }
    },
    // 2. 分页查询
    async findByPage() {
      const {data:res} = await employeeApi.findByPage(this.page,this.pageSize)
      console.log(res)
      if (res.code === 200) {
        this.employeeList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    // 3. 查询所有部门
    async findAllDepart() {
      const {data:res} = await departApi.findAllDepart()
      if (res.code === 200) {
        this.departList = res.data.list
      }
    },
    // 4. 条件查询带分页
    async search(){
      this.employeeSearch.edepart = this.employeeSearch.id;
      const {data:res} = await employeeApi.search(this.page,this.pageSize,this.employeeSearch)
      console.log(res)
      if (res.code === 200) {
        this.employeeList = res.data.pr.rows
        this.total = res.data.pr.total
      }

    },
    // 当pageSize大小发生改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.search()
      console.log(`每页 ${val} 条`);
    },
    // 当页码page发生改变时触发
    handleCurrentChange(val) {
      this.page = val;
      this.search()
      console.log(`当前页: ${val}`);
    },
    handleEdit(index, row) {
      this.title = "编辑员工信息"
      this.employee = row
      this.dialogFormVisible = true
    },

    //删除员工
    handleDelete(index, row) {
      this.ids = []
      if(row){  // 代表删除单个员工
        this.ids.push(row.eid)
      }else{  //undefined时表示批量删除的情况
        this.ids = this.multipleSelection.map(m => m.eid)
      }
      this.$confirm(`是否真的要删除学号为${this.ids}的员工吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {       // 点击了"确定"按钮后执行
        let _this = this//其实和this.search()是等效的，但是这样编写可以使代码更加清晰，特别是在.then()里面又嵌套接口的情况，并且有可以避免意想不到的错误。
        employeeApi.deleteEmployee(this.ids)
            .then(({data:res}) => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    // 重新加载数据
                    _this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {     // 点击了"取消"按钮后执行
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addEmployee() {
      this.title = "添加员工信息"
      this.employee = {}
      this.dialogFormVisible = true
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("选中信息"+JSON.stringify(this.multipleSelection))
    },
    saveEmployee() {
      this.$refs.ruleForm.validate(async valid => {
        let url = "/employee/add"      // 默认地址是添加员工
        let method = "post"           // 添加是post请求
        if(this.employee.eid){
          url = "/employee/update"    // 如果有值就改为修改员工
          method = "put"             // 修改是put请求
        }
        if (valid) {
          console.log(this.employee)
          this.employee.edepart = this.employee.id;
          const {data:res} = await employeeApi.save(url,method,this.employee)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message,
              onClose: () => {
                this.dialogFormVisible = false
                this.search()
              }
            })
          }else{
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
  }
}
</script>

<style>

#app{
  display: flex;
  justify-content: center;
}
.el-card{
  width: 90%;
}
.el-pagination{
  margin-top: 20px;
  text-align: right;
}
</style>
